# ArtistScreen - This screen allows user to browse music of one specific artist
# Copyright (C) 2007 Lauri Taimila
# 
# Entertainer is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# Entertainer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

__licence__ = "GPLv2"
__copyright__ = "2007, Lauri Taimila"
__author__ = "Lauri Taimila <lauri@taimila.com>"

import os
import gtk
import pango
import clutter

from frontend.gui.screens.screen import Screen
from frontend.gui.transitions.transition import Transition

# Widgets
from frontend.gui.widgets.tabs_menu import TabsMenu
from frontend.gui.widgets.text_menu import TextMenu
from frontend.gui.widgets.image_menu import ImageMenu

from frontend.gui.widgets.text_menu_item import TextMenuItem
from frontend.gui.widgets.image_menu_item import ImageMenuItem
from frontend.gui.widgets.justified_text_menu_item import JustifiedTextMenuItem

from frontend.gui.widgets.list_indicator import ListIndicator

# Music library
from frontend.medialibrary.music import MusicLibrary
from frontend.medialibrary.music import Track
from frontend.medialibrary.music import Album

class ArtistScreen(Screen):
    """
    ArtistScreen
    
    Screen that allows user to browse music by artist.
    """
    
    def __init__(self, ui, frontend, artist):
        """
        Initialize screen
        
        @param frontend: FrontendClient object
        @param theme: Theme object
        """
        self.ui = ui
        self.frontend = frontend
        self.theme = frontend.getTheme()
        self.library = self.frontend.get_music_library()
        self.artist = artist
        self.group = clutter.Group()
        
        # Screen Title (Displayed at the bottom left corner)
        screen_title = clutter.Label()
        screen_title.set_font_name(self.theme.getFont() + ' 100px')
        screen_title.set_color(self.theme.getColor("screentitle"))
        screen_title.set_text(self.artist)
        screen_title.set_name("screen_title")
        (screen_title_width, screen_title_height) = screen_title.get_size()
        screen_title_x = 0
        screen_title_y = ui.STAGE_HEIGHT - screen_title_height + 20
        screen_title.set_position(screen_title_x, screen_title_y)
        screen_title.show()
        self.group.add(screen_title)
        
        # Create tabs and content
        self._create_albums_tab()
        self._create_tracks_tab()
        self._create_tabs()
        
        # Activate albums tab when screen is opened
        self.current_tab = "albums"
        self.albums_tab.show()
        
        self.group.show()
        ui.getStage().add(self.group)
    
    def _create_tabs(self):
        """
        Create tab bar of the screen. Tabs: Movies, TV-Series, Video clips
        """
        self.tabs = TabsMenu(self.theme, 
                        self.frontend.get_configuration().show_effects())
        self.tabs.set_item_size(300, 60)
        self.tabs.set_visible_column_count(4)
        
        tab1 = JustifiedTextMenuItem(300, 60, self.theme, "Albums", JustifiedTextMenuItem.CENTER)
        tab1.set_userdata("albums")
        self.tabs.add_actor(tab1)
        
        tab2 = JustifiedTextMenuItem(300, 60, self.theme, "Tracks", JustifiedTextMenuItem.CENTER)
        tab2.set_userdata("tracks")
        self.tabs.add_actor(tab2)
        
        self.tabs.set_position(383, 40)
        self.tabs.set_active(True)
        self.tabs.show()
        self.group.add(self.tabs)
    
    def _create_tracks_tab(self):
        """
        Create a list of tracks
        """
        self.tracks_tab = clutter.Group()
        self.tracks_menu = TextMenu(self.theme, 
                               self.frontend.get_configuration().show_effects())
        self.tracks_menu.set_item_size(400, 60)
        cursor = clutter.Rectangle()
        cursor.set_color((0,0,0,0))
        self.tracks_menu.set_cursor(cursor)
        
        tracks = self.library.get_tracks_by_artist(self.artist)
        for track in tracks:
            item = JustifiedTextMenuItem(400, 60, self.theme, track.get_title())
            item.set_userdata(track)
            self.tracks_menu.add_actor(item)
        
        self.tracks_menu.set_orientation(TextMenu.HORIZONTAL)
        self.tracks_menu.set_row_count(7)
        self.tracks_menu.set_visible_column_count(3)
        
        self.tracks_menu.set_position(80,160)
        self.tracks_menu.set_active(False)
        self.tracks_menu.show()
        
        if self.frontend.get_configuration().show_effects():
            self.tracks_menu.set_animate(True)
        
        self.tracks_tab.add(self.tracks_menu)
        
        # Create artist label
        self.track_title = clutter.Label()
        self.track_title.set_text(" ")
        self.track_title.set_font_name(self.theme.getFont() + ' 32px')
        self.track_title.set_color(self.theme.getColor("title"))
        self.track_title.set_line_wrap(False)
        #self.track_title.set_ellipsize(pango.ELLIPSIZE_END)
        self.track_title.set_position(300, 610)
        self.track_title.set_size(500,40)
        self.track_title.show()
        self.tracks_tab.add(self.track_title)
        
        self.track_number = clutter.Label()
        self.track_number.set_text(" ")
        self.track_number.set_font_name(self.theme.getFont() + ' 28px')
        self.track_number.set_color(self.theme.getColor("subtitle"))
        self.track_number.set_position(300, 660)
        self.track_number.set_size(500,40)
        self.track_number.set_line_wrap(False)
        #self.track_number.set_ellipsize(pango.ELLIPSIZE_END)
        self.track_number.show()
        self.tracks_tab.add(self.track_number)
        
        self.track_length = clutter.Label()
        self.track_length.set_text(" ")
        self.track_length.set_font_name(self.theme.getFont() + ' 28px')
        self.track_length.set_color(self.theme.getColor("subtitle"))
        self.track_length.set_line_wrap(False)
        #self.track_length.set_ellipsize(pango.ELLIPSIZE_END)
        self.track_length.set_position(300, 700)
        self.track_length.set_size(500,40)
        self.track_length.show()
        self.tracks_tab.add(self.track_length)
        
        # Create artis menu list indicator
        self.track_li = ListIndicator(200, 34, self.theme, ListIndicator.HORIZONTAL)
        self.track_li.set_position(1270 - self.track_li.get_width(), 610)
        self.track_li.set_delimiter(" | ")
        self.track_li.set_maximum(self.tracks_menu.get_number_of_items())
        self.track_li.set_current(1)
        self.track_li.show()
        self.tracks_tab.add(self.track_li)
        
        self.group.add(self.tracks_tab)
        
    def _create_albums_tab(self):
        """
        Create a list of albums
        """
        self.albums_tab = clutter.Group()
        albums = self.library.get_albums_by_artist(self.artist)
        
        if len(albums) < 4:
            tex_size = 400
            row_count = 1
            visible = 3
        elif len(albums) < 13:
            tex_size = 200
            row_count = 2
            visible = 6
        else:
            tex_size = 150
            row_count = 3
            visible = 8
        
        # Create albums menu
        self.album_menu = ImageMenu(self.theme)
        self.album_menu.set_row_count(row_count)
        self.album_menu.set_visible_column_count(visible)
        self.album_menu.set_item_size(tex_size, tex_size)
        
        # Default texture
        default_cover = clutter.Texture()
        buffer = gtk.gdk.pixbuf_new_from_file(self.theme.getImage("default_album_art"))
        default_cover.set_pixbuf(buffer)
        
        for album in albums:
            if album.has_album_art():
                texture = clutter.Texture()
                buffer = gtk.gdk.pixbuf_new_from_file(album.get_album_art_url())
                texture.set_pixbuf(buffer)
            else:
                texture = clutter.CloneTexture(default_cover)
            
            item = ImageMenuItem(tex_size, tex_size, texture)
            item.set_userdata(album)
            self.album_menu.add_actor(item)
        
        
        self.album_menu.set_position(80,140)
        self.album_menu.set_active(False)
        self.album_menu.show()
        
        if self.frontend.get_configuration().show_effects():
            self.album_menu.set_animate(True)
        
        self.albums_tab.add(self.album_menu)
        
        # Create album menu list indicator
        self.album_li = ListIndicator(200,34, self.theme, ListIndicator.HORIZONTAL)
        self.album_li.set_position(1270 - self.album_li.get_width(), 610)
        self.album_li.set_delimiter(" | ")
        self.album_li.set_maximum(self.album_menu.get_number_of_items())
        self.album_li.set_current(1)
        self.album_li.show()
        self.albums_tab.add(self.album_li)
        
        # Create album information (displays current menuitem information)
        self.album_title = clutter.Label()
        self.album_title.set_text(" ")
        self.album_title.set_font_name(self.theme.getFont() + ' 32px')
        self.album_title.set_color(self.theme.getColor("title"))
        self.album_title.set_line_wrap(False)
        #self.album_title.set_ellipsize(pango.ELLIPSIZE_END)
        self.album_title.set_position(300, 610)
        self.album_title.set_size(500,40)
        self.album_title.show()
        self.albums_tab.add(self.album_title)
        
        self.album_artist = clutter.Label()
        self.album_artist.set_text(" ")
        self.album_artist.set_font_name(self.theme.getFont() + ' 28px')
        self.album_artist.set_color(self.theme.getColor("subtitle"))
        self.album_artist.set_line_wrap(False)
        #self.album_artist.set_ellipsize(pango.ELLIPSIZE_END)
        self.album_artist.set_position(300, 660)
        self.album_artist.set_size(500,40)
        self.album_artist.show()
        self.albums_tab.add(self.album_artist)
        
        self.album_tracks = clutter.Label()
        self.album_tracks.set_text(" ")
        self.album_tracks.set_font_name(self.theme.getFont() + ' 28px')
        self.album_tracks.set_color(self.theme.getColor("subtitle"))
        self.album_tracks.set_position(300, 700)
        self.album_tracks.set_size(500,40)
        self.album_tracks.set_line_wrap(False)
        #self.album_tracks.set_ellipsize(pango.ELLIPSIZE_END)
        self.album_tracks.show()
        self.albums_tab.add(self.album_tracks)
        
        self.group.add(self.albums_tab)
    
    def _update_album_info(self, album):
        """
        Update album information. This information is displayed on albums tab.
        @param album: Album object
        """
        self.album_title.set_text(album.get_title())
        self.album_artist.set_text(album.get_artist())
        self.album_tracks.set_text(str(album.get_number_of_tracks()) + " tracks")
       
    def _update_track_info(self, track):
        """
        Update track information. This information is displayed on track tab.
        @param track: Track object
        """
        self.track_title.set_text(track.get_title())
        self.track_length.set_text(str(track.get_length() / 60) + ":" + str(track.get_length() % 60).zfill(2))
        self.track_number.set_text("Track " + str(track.get_tracknumber()) + " from " + track.get_album().get_title())
       
    def _change_tab(self):
        """
        Change tab. This is called when user changes the screen tab.
        """
        self.tracks_tab.hide()
        self.albums_tab.hide()
            
        self.current_tab = self.tabs.get_current_menuitem().get_userdata()
        if self.current_tab == "tracks":
            self.tracks_tab.show()
        else:
            self.albums_tab.show()
        
    def get_group(self):
        """
        Get all actors of the screen.
        @return clutter.Group 
        """
        return self.group

    def get_type(self):
        """Return screen type."""
        return Screen.NORMAL
    
    def get_name(self):
        """Return screen name (human readble)"""
        return "ArtistScreen"
    
    def handle_key_press_event(self, event):   
        """ Handle key pressed event."""
        #UP KEY
        if event.keyval == clutter.keysyms.Up:
            if self.current_tab == "tracks":
                if self.tracks_menu.get_cursor_position()[1] == 0:
                    self.tracks_menu.set_active(False)
                    self.tabs.set_active(True)
                else:
                    self.tracks_menu.move(self.album_menu.UP)
                    self._update_track_info(self.tracks_menu.get_current_menuitem().get_userdata())
                    self.track_li.set_current(self.tracks_menu.get_current_postition() + 1)
            
            elif self.current_tab == "albums":
                if self.album_menu.get_cursor_position()[1] == 0:
                    self.album_menu.set_active(False)
                    self.tabs.set_active(True)
                else:
                    self.album_menu.move(self.album_menu.UP)
                    self._update_album_info(self.album_menu.get_current_menuitem().get_userdata())
                    self.album_li.set_current(self.album_menu.get_current_postition() + 1)
        
        #DOWN KEY  
        elif event.keyval == clutter.keysyms.Down:
            # Activate tab menu if tab bar was active
            if self.tabs.is_active():
                self.tabs.set_active(False)
                if self.current_tab == "tracks":
                    self.tracks_menu.set_active(True)
                    self._update_track_info(self.tracks_menu.get_current_menuitem().get_userdata())
                elif self.current_tab == "albums":
                    self.album_menu.set_active(True)
                    self._update_album_info(self.album_menu.get_current_menuitem().get_userdata())
                return
            
            if self.current_tab == "tracks":
                self.tracks_menu.move(self.tracks_menu.DOWN)
                self._update_track_info(self.tracks_menu.get_current_menuitem().get_userdata())
                self.track_li.set_current(self.tracks_menu.get_current_postition() + 1)
            elif self.current_tab == "albums":
                self.album_menu.move(self.album_menu.DOWN)
                self._update_album_info(self.album_menu.get_current_menuitem().get_userdata())
                self.album_li.set_current(self.album_menu.get_current_postition() + 1)
        
        #LEFT KEY
        elif event.keyval == clutter.keysyms.Left:
            if self.tabs.is_active():
                self.tabs.move(self.tabs.LEFT)
                self._change_tab()
            elif self.current_tab == "tracks":
                self.tracks_menu.move(self.tracks_menu.LEFT)
                self._update_track_info(self.tracks_menu.get_current_menuitem().get_userdata())
                self.track_li.set_current(self.tracks_menu.get_current_postition() + 1)
            elif self.current_tab == "albums":
                self.album_menu.move(self.album_menu.LEFT)
                self._update_album_info(self.album_menu.get_current_menuitem().get_userdata())
                self.album_li.set_current(self.album_menu.get_current_postition() + 1)
        
        # RIGHT KEY
        elif event.keyval == clutter.keysyms.Right:
            if self.tabs.is_active():
                self.tabs.move(self.tabs.RIGHT)
                self._change_tab()  
            elif self.current_tab == "tracks":
                self.tracks_menu.move(self.tracks_menu.RIGHT)
                self._update_track_info(self.tracks_menu.get_current_menuitem().get_userdata())
                self.track_li.set_current(self.tracks_menu.get_current_postition() + 1)
            elif self.current_tab == "albums":
                self.album_menu.move(self.album_menu.RIGHT)
                self._update_album_info(self.album_menu.get_current_menuitem().get_userdata())
                self.album_li.set_current(self.album_menu.get_current_postition() + 1)
        
        # RETURN KEY
        elif event.keyval == clutter.keysyms.Return:
            if self.current_tab == "tracks":
                track = self.tracks_menu.get_current_menuitem().get_userdata()
                self.ui.changeScreen(self.ui.createScreen("audio_play", track), Transition.FORWARD)
            elif self.current_tab == "albums":
                album = self.album_menu.get_current_menuitem().get_userdata()
                self.ui.changeScreen(self.ui.createScreen("music_album", album), Transition.FORWARD)
